

#include "kev.h"
#include <iostream>
#include "solid.h"
#include "hedmodel.h"
#include "face.h"
#include "loop.h"
#include "point.h"
#include "vertex.h"
#include "halfedge.h"
#include "edge.h"


KEV::KEV(HEDModel& _model, int _s, int _f, int _v1, int _v2)
: he1( NULL )
, he2( NULL )
{
  Solid* solid = NULL;
  Face *f = NULL;
  // find needed objects, check existence
  if( (solid = _model.getsolid(_s)) == NULL )
  {
    std::cout << "kev: solid " << _s << " not found. \n";
    //return(ERROR);
  }
  if( (f = _model.fface(solid,_f)) == NULL )
  {
    std::cout << "kev: face " << _f << " not found in solid " << _s << ". \n";
    //return(ERROR);
  }
  if( (he1 = _model.fhe(f,_v1,_v2)) == NULL )
  {
    std::cout << "kev: edge " << _v1 << " - " << _v2 << " not found in face " << _f << ". \n";
    //return(ERROR);
  }

  he2 = he1->mate();

  // check that edge occurs in only one loop 
  if(he1->getLoop() != he2->getLoop())
  {
    std::cout << "kev: edge " << _v1 << " - " << _v2 << " not in same loop. \n";
    //return(ERROR);
  }
  // check that v2 is an endpoint 
  if(he1->getNxt() != he2)
  {
    std::cout << "kev: vertex " << _v2 << " is not an endpoint. \n";
    //return(ERROR);
  }

  // call lkev() to do the real work
  //lkev(he2, he1);
}


KEV::KEV(HalfEdge* _he1, HalfEdge* _he2)
: he1( _he1 )
, he2( _he2 )
{
  if( _he1 == NULL || _he2 == NULL )
  {
    std::cout << "[W] Two half-edges are needed for this Euler operator work!" << std::endl;
    return;
  }
  if( _he1->getEdg() != _he2->getEdg() )
  {
    std::cout << "[W] Given half-edges must lie over the same edge!" << std::endl;
    return;
  }        
  if( _he1 == _he2 )
  {
    std::cout << "[W] Given half-edges must be different!" << std::endl;
    return;
  }      
}




void
KEV::execute()
{
  std::cout << "\nKEV::execute() \n";

  HalfEdge* he = he2->getNxt();
  while(he != he1)
  {
    he->setVtx( he2->getVtx() );
    he = he->mate()->getNxt();
  }

  he1->getLoop()->setLedg( he1->delhe() );
  he2->getLoop()->setLedg( he2->delhe() );
  he2->getVtx()->setVedge( he2->getNxt() );
  if( !he2->getVtx()->getVEdge()->getEdg() )
    he2->getVtx()->setVedge( NULL );
  //he1->wloop->ledg = delhe(he1);
  //he2->wloop->ledg = delhe(he2);
  //he2->vtx->vedge = he2->nxt;
  //if(!he2->vtx->vedge->edg) he2->vtx->vedge = (HalfEdge *)NIL;

  //del(EDGE, (Node *)he1->edg, (Node *)he1->wloop->lface->fsolid);
  //del(VERTEX, (Node *)he1->vtx, (Node *)he1->wloop->lface->fsolid);
  delete he1->getEdg();
  delete he1->getVtx();
  delete he1;
  if( he2->getVtx()->getVEdge() )
    delete he2;
  else
    he2->getVtx()->setVedge( he2 );
}


void
KEV::unExecute()
{
  std::cout << "\nKEV::unExecute() NOT IMPLEMENTED!\n";
}
